<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">

          <el-form-item label="用户账号：">
            <el-input v-model="listQuery.userName"
                      placeholder="请输入"
                      clearable />
          </el-form-item>





        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询</el-button>
          <el-button size="mini"  type="info"
                     @click="reset">重置</el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>
        <el-table-column prop="userName"
                         label="用户账号" >
        </el-table-column>

        <el-table-column prop="ipAddress"
                         label="登录ip" >
        </el-table-column>
        <el-table-column prop="loginCount"
                         label="登录次数" >
        </el-table-column>

        <el-table-column prop="createDate"
                         label="最近一次登陆时间" >
        </el-table-column>

        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="success" size="mini" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>

            </div>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList" />
    </div>


  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 当然你也可以为了方便使用，将它注册到全局

import bus from '@/utils/eventBus'
import searchBox from '@/components/searchBox.vue'

import * as yearinfo from '@/api/yearinfo'

import * as userInfo from "@/api/userinfo";

export default {
  name: 'AdminUser',
  components: { Pagination, searchBox },
  directives: { waves },
  filters: {

  },
  data () {
    return {
      list: null,
      areaList: null,
      total: 0,
      formLabelWidth: '120px',
      form:{
        thing:'',
        year:'',
        proIdList:[],
        proId:',',
      },
      listQuery: { // 查询列表时的参数对象
        pageNumber: 1,
        pageSize: 50,
        appName: process.env.VUE_APP_APP_NAME,
        tenantIdList: []
      },
    dialogFormVisible: false,
      dialogStatus: '',
      yearList: [
        {label: '2021', value: '2021'},
        {label: '2022', value: '2022'},
        {label: '2023', value: '2023'},
        {label: '2024', value: '2024'},
        {label: '2025', value: '2025'},
        {label: '2026', value: '2026'},
        {label: '2027', value: '2027'},
        {label: '2028', value: '2028'},
        {label: '2029', value: '2029'},
        {label: '2030', value: '2030'},
        {label: '2031', value: '2031'},
        {label: '2032', value: '2032'},
        {label: '2033', value: '2033'},
        {label: '2034', value: '2034'},
        {label: '2035', value: '2035'},
        {label: '2036', value: '2036'},
        {label: '2037', value: '2037'},
        {label: '2038', value: '2038'},
        {label: '2039', value: '2039'},
        {label: '2040', value: '2040'},
      ],

      proList: [],
      thingList: [
        {label: '春粮收购', value: '春粮收购'},
        {label: '夏粮收购', value: '夏粮收购'},
        {label: '秋粮收购', value: '秋粮收购'},
        {label: '冬粮收购', value: '冬粮收购'},

      ],
    }
  },
  computed: {
    ...mapGetters([
      'selectedTenantId',
      'tenantList'
    ])
  },
  created () {

    // 监听 租户改变的事件,选择不同租户后,立马刷新数据
    bus.$on('selectedTenantIdChanged', () => {
      console.log("selectedTenantIdChanged事件触发...")
      this.getList()
    })
    this.getList()
  },
  mounted () {
    // 测试用
    // var that = this
    // setTimeout(function() {
    //   that.dialogFormVisible = true
    // }, 5000)
  },
  beforeDestroy () { // 当路由切换到其他页面时触发
    bus.$off('selectedTenantIdChanged')
  },
  methods: {
    async getList () { // 获取列表数据
      this.listQuery.tenantIdList = []
      if (this.selectedTenantId == undefined) {//当前选中所有的租户
        this.tenantList.forEach((tenant, index) => {
          this.listQuery.tenantIdList.push(tenant.id)
        })
      } else {
        this.listQuery.tenantIdList.push(this.selectedTenantId)
      }

      const { content } = await userInfo.loginList(this.listQuery)
      this.list = content.list
      this.total = content.totalCounts
    },




    handleCreate() {
      this.form = {};

      this.dialogStatus = 'create'
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

    },
    handleUpdate(row) {
      this.form = row;
      let yearName = row.yearName.split('-');
      this.$set(this.form,'year',yearName[0])
      this.$set(this.form,'thing',yearName[1])
      this.$set(this.form,'stopDateStr',row.stopDate)
      this.$set(this.form,'startDateStr',row.startDate)

      if(row.proId!=null){
        let proIdList = row.proId.split(",");
        this.$set(this.form,'proIdList',proIdList);
      }

      console.log('form',row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

    },


    handleDelete(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        yearinfo.deleteYearInfo(row.id).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
      })

    },

    createData() {
      this.form.yearName = this.form.year+'-'+this.form.thing;

      if(this.form.proIdList.length>0){
        let proId='1,';
        for(let i=0;i<this.form.proIdList.length;i++){
          proId+=(this.form.proIdList[i]+',');

        }
        this.form.proId= proId.substring(2,proId.length - 1).toString();
        this.form.proIdList= null;
      }
      console.log('this.form',this.form)
      this.$refs['dataForm'].validate((valid) => {//验证表单是否为空
        if (valid) {
          this.form.tenantId = this.$store.getters.selectedTenantId
          yearinfo.createYearInfo(this.form).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },

    updateData() {
      this.form.yearName = this.form.year+'-'+this.form.thing;
      if(this.form.proIdList.length>0){
        let proId='1,';
        for(let i=0;i<this.form.proIdList.length;i++){
          proId+=(this.form.proIdList[i]+',');

        }
        this.form.proId= proId.substring(2,proId.length - 1).toString();
        this.form.proIdList= null;
      }
      console.log(this.form);
      this.$refs['dataForm'].validate((valid) => {//验证表单是否为空
        if (valid) {
          yearinfo.updateYearInfo(this.form).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },


    handleFilter () {
      this.listQuery.pageNumber = 1
      this.listQuery.listQuery = this.form.yearName;
      this.getList()
    } ,
    reset () {
      this.listQuery = {}
      this.getList()
    },
    cancel() {
      this.dialogFormVisible = false;
      this.getList();
    }
  }
}
</script>

<style scoped>
.app-select {
  margin-bottom: 20px;
}
</style>
